package com.collabscm.pf.crypt.impl;

import it.sauronsoftware.base64.Base64;

import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.util.ArrayList;
import java.util.List;

import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.KeyGenerator;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;

import com.collabscm.pf.crypt.SymmetricEncryption;

/**
 * AES加密算法的实现
 * @author Zeng Raoxing
 */
public class AESEncryption implements SymmetricEncryption {
	
	public static void main(String[] args) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, IllegalBlockSizeException, BadPaddingException {
//		Security.addProvider(new BouncyCastleProvider());
		KeyGenerator kgen = KeyGenerator.getInstance("AES"); 
		kgen.init(128, new SecureRandom("password".getBytes())); 
		SecretKey skey = kgen.generateKey(); 
		byte[] raw = skey.getEncoded(); 
		SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES"); 
		Cipher cipher = Cipher.getInstance("AES"); 
		cipher.init(Cipher.ENCRYPT_MODE, skeySpec);
		int total = 1000;
		char[] chars = new char[] {'a', 'b', 'c', 'd', 'e', 'f', 'g',
				                   'h', 'i', 'j', 'k', 'l', 'm', 'n',
				                   'o', 'p', 'q', 'r', 's', 't', 
				                   'u', 'v', 'w', 'x', 'y', 'z'};
		List<String> srcList = new ArrayList<String>(total);
		for(int i=0; i<total; i++) {
			int pos = 0;
			StringBuffer sb = new StringBuffer();
			for(int j=0; j<10; j++) {
				pos = (int) (26 * Math.random());
				sb.append(chars[pos]);
			}
			srcList.add(sb.toString());
		} 
		List<String> resultList = new ArrayList<String>(total);
		long startTime = System.currentTimeMillis();
		for(int i=0; i<total; i++) {
			byte[] cs = cipher.doFinal(srcList.get(i).getBytes());
			
			resultList.add(new String(Base64.encode(cs)));
		}
		System.out.println("加密" + total + "个字符串用时：" + (System.currentTimeMillis() - startTime) + "ms.");
//		for(int i=0; i<total; i++) {
//			System.out.println(srcList.get(i) + ":" + resultList.get(i));
//			if(i > 10) break;
//		}
	}

	@Override
	public String decrypt(String ciphertext) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public String encrypt(String plainText) {
		// TODO Auto-generated method stub
		return null;
	}

}
